package com.tbvtc.agriculturalcreditchainserver2025.Interceptor;

import com.tbvtc.agriculturalcreditchainserver2025.comment.Token.JwtUtil;
import com.tbvtc.agriculturalcreditchainserver2025.login.LoginUser;
import com.tbvtc.agriculturalcreditchainserver2025.login.LoginUserHolder;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //1. 获取请求url。
        log.info("当前请求路径：{}", request.getRequestURI());
        String url = request.getRequestURL().toString();
        log.info(url);
        //      2. 判断请求url中是否包含login，如果包含，说明是登录操作，放行。
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }
        if (url.contains("login")) { //登录请求
            log.info("登录请求 , 直接放行");
            return true;
        }
        //3. 获取请求头中的令牌（token）。
        log.info("拦截请求: {}", request.getRequestURI()); // 请求时查看日志
        String token = request.getHeader("Authorization");
        //String token1=request.getHeader("access-token");
        //5. 解析token，如果解析失败，返回错误结果（未登录）。
        try {
            JwtUtil.parseToken(token);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析令牌失败, 返回错误结果");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
        //6. 放行。
        log.info("令牌合法, 放行");
        Claims claims = JwtUtil.parseToken(token);
        String phoen = claims.get("phone", String.class);
        Long userId = claims.get("userId", Long.class);
        LoginUserHolder.setLoginUser(new LoginUser(phoen, userId)); // 把用户信息放入ThreadLocal中
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginUserHolder.clear();
    }

}